/**
 * 
 */
package net.sf.rose.web.spring.servlet.handler;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;

/**
 * @author fengjian
 * 
 */
public class AbstractHandler extends URLHandler {

	/**
	 * 
	 */
	private Method[] methods = null;

	/**
	 * 
	 */
	public AbstractHandler() {
		methods = this.getClass().getMethods();
	}

	/**
	 * 
	 */
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String method = null;
		ModelAndView mv = null;
		boolean flag = false;

		try {
			method = request.getParameter("method");
			if (method != null) {
				Method m = getMethod(method);
				if (m != null) {
					mv = (ModelAndView) m.invoke(this, request, response);
					flag = true;
				}
			}
			if (!flag) {
				method = request.getMethod();
				if (method.equals("GET")) {
					mv = this.doGet(request, response);
				} else if (method.equals("POST")) {
					mv = this.doPost(request, response);
				}
			}
		} catch (Exception e) {
			throw e;
		} finally {
		}
		//if (mv == null) {
			//mv = new ModelAndView(getViewName());
		//}
		return mv;
	}

	/**
	 * 
	 */
	public ModelAndView doGet(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		return new ModelAndView(getViewName());
	}

	/**
	 * 
	 */
	public ModelAndView doPost(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		return new ModelAndView(getViewName());
	}

	/**
	 * 
	 */
	private Method getMethod(String name) {
		for (int i = 0; i < methods.length; i++) {
			if (methods[i].getName().equals(name)) {
				return methods[i];
			}
		}
		return null;
	}
}
